package com.yowasa.xiuxian.engine.message.map;

import cn.hutool.core.lang.WeightRandom;
import com.google.common.collect.Lists;
import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.CommonEngine;
import com.yowasa.xiuxian.engine.TravelEngine;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.engine.travel.AdventureInterface;
import com.yowasa.xiuxian.entity.bo.user.UserBO;
import com.yowasa.xiuxian.entity.enums.MapEnum;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.RedisService;
import com.yowasa.xiuxian.service.helper.MessageHelper;
import com.yowasa.xiuxian.service.helper.UserHelper;
import com.yowasa.xiuxian.util.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@CMD(name = "/游历")
public class TravelHandler extends CmdMessageHandler {
    public static final Logger logger = LoggerFactory.getLogger(TravelHandler.class);
    @Autowired
    private UserHelper userHelper;

    @Autowired
    private MessageHelper messageHelper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private TravelEngine travelEngine;

    @Value("${xiuxian.rate.happyTravel}")
    private int happyTravelRate;

    @Override
    public void execute(SendMessage message) {
        UserBO user = userHelper.checkOpUserAll(message);
        Integer local = user.getLocal();
        MapEnum map = MapEnum.getById(local);
        List<AdventureInterface> adventureInterfaces = CommonEngine.ADVENTURE_MAP.getOrDefault(map, Lists.newArrayList());
        adventureInterfaces = adventureInterfaces.stream().filter(e -> e.limitCheck(user)).collect(Collectors.toList());
        int threshold = 10 * happyTravelRate * user.getUserAttr().getLuc() / 50;
        if(map.getType() == 4){
            String redisKey = "mys:xiuxian:userInfo:mijingTravel:"+user.getUserId();
            if(redisService.hasKey(redisKey)){
                threshold *= cn.hutool.core.util.RandomUtil.randomInt(2,5);
            }else {
                throw new HandlerException("秘境已经关闭，请离开吧~");
            }
        }

        if (!CollectionUtils.isEmpty(adventureInterfaces)) {
            if (RandomUtil.randomInt(1,1000) <= threshold) {
                AdventureInterface choice = randomGet(adventureInterfaces);
                String msg = choice.exec(user);
                userHelper.saveUserInfo(user);
                if (choice.isConflict()) {
                    messageHelper.replyMys(message, msg);
                    return;
                }
                messageHelper.replyMys(message, msg);
            }
        }
        String exec = travelEngine.exec(user);
        userHelper.saveUserInfo(user);
        messageHelper.replyMys(message, exec);
    }

    public String desc(){
        return new StringBuffer().append("在当前所处的位置进行游历，游历可能触发奇遇\n")
                .append("仙缘越高，触发奇遇的概率越高，每个地点都有不同的奇遇\n")
                .append("在城市中游历会获得摩拉，在村子里游历会获得历练值，在野外游历会与怪物战斗")
                .toString();

    }

    public AdventureInterface randomGet(List<AdventureInterface> adventureInterfaces){
        List<WeightRandom.WeightObj<AdventureInterface>> list = new ArrayList<WeightRandom.WeightObj<AdventureInterface>>();
        adventureInterfaces.forEach(e -> {
            logger.info("奇遇:{}，权重:{}",e.getClass().getName(),e.weight());
            list.add(new WeightRandom.WeightObj<>(e,e.weight()));
        });
        WeightRandom<AdventureInterface> one = cn.hutool.core.util.RandomUtil.weightRandom(list);
        AdventureInterface next = one.next();
        return next;
    }
}
